import { createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import rootReducer from './reducers';

export default function configureStore(initialState = {}) {
  const composeEnhancers =
    typeof window !== 'undefined' && window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      ? window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__
      : compose;

  let store;

  if (typeof window !== 'undefined') {
    // 只在客户端使用 redux-persist
    const { persistStore, persistReducer } = require('redux-persist');
    const storage = require('redux-persist/lib/storage').default;

    const persistConfig = {
      key: 'root',
      storage,
    };

    const persistedReducer = persistReducer(persistConfig, rootReducer);
    store = createStore(
      persistedReducer,
      initialState,
      composeEnhancers(applyMiddleware(thunk))
    );

    const persistor = persistStore(store);

    return { store, persistor };
  } else {
    // 服务器端不使用 redux-persist
    store = createStore(
      rootReducer,
      initialState,
      composeEnhancers(applyMiddleware(thunk))
    );
    return { store };
  }
}
